package router

import (
	"bytes"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

// SetupRouter 路由设置
func SetupRouter() *gin.Engine {
	r := gin.Default()
	r.Use(requestRecord())
	api := r.Group("/api")
	api.GET("/test", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "ok"})
		println("HELLO")
	})
	return r
}

// 日志中间件
func requestRecord() gin.HandlerFunc {
	return func(c *gin.Context) {
		logger := logrus.New()
		//logger.SetReportCaller(true)
		logger.SetFormatter(&logrus.JSONFormatter{})
		clientIP := c.ClientIP()
		method := c.Request.Method
		path := c.Request.URL.Path
		var reqParams string
		var requestBody bytes.Buffer
		// 备份原始的请求体读取器
		teeReader := io.TeeReader(c.Request.Body, &requestBody)
		// 将备份后的读取器重新赋值给请求体
		c.Request.Body = ioutil.NopCloser(teeReader)
		if method == "GET" {
			reqParams = c.Request.URL.RawQuery
		} else if method == "POST" {
			contentType := c.Request.Header.Get("Content-Type")
			if strings.Contains(contentType, "application/json") {
				jsonData, _ := ioutil.ReadAll(&requestBody)
				reqParams = string(jsonData)
			} else {
				reqParams = c.Request.PostForm.Encode()
			}
		}
		file, err := os.OpenFile("2016_error.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			panic(err)
		}
		// 设置日志输出到文件
		logger.SetOutput(file)
		// 使用logrus记录日志
		entry := logger.WithFields(logrus.Fields{
			"method":    method,
			"path":      path,
			"client_ip": clientIP,
			"params":    reqParams,
			"source":    "default",
		})
		entry.Info("request")
		// 处理请求
		c.Next()
	}
}
